using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using Microsoft.VisualStudio.TeamSystem.Data.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Testing.Core
{
	public static class TestingDatabase
	{
		static readonly List<DatabaseTestContext> contexts = new List<DatabaseTestContext>();

		public static void EnsureDatabases()
		{
			contexts.Clear();
			AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
			AppDomain.CurrentDomain.SetData( "DataDirectory", Environment.CurrentDirectory );
			foreach ( ConnectionStringSettings settings in ConfigurationManager.ConnectionStrings )
			{
				DatabaseTestContext context = new DatabaseTestContext( settings.Name );
				if ( context.EnsureDatabase() )
				{
					contexts.Add( context );
				}
			}
			
			try
			{
				DatabaseTestClass.TestService.DeployDatabaseProject();
			}
			catch( AssertFailedException )
			{
			}
		}

		static void CurrentDomain_DomainUnload(object sender, EventArgs e)
		{
			contexts.ForEach( item => item.Dispose() );
			contexts.Clear();
		}
	}
}